package com.eco.service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.config.dao.EquMoldDao;
import com.config.dao.EquipmentDao;
import com.config.entity.EquMold;
import com.config.entity.Equipment;
import com.data.dao.ChargeMonthDao;
import com.data.dao.ChargeWeekDao;
import com.data.dao.StateDayDao;
import com.data.dao.StateMinDao;
import com.data.dao.StateMonthDao;
import com.data.dao.StateWeekDao;
import com.data.entity.ChargeMonth;
import com.data.entity.ChargeWeek;
import com.data.entity.StateMonth;
import com.data.entity.StateWeek;
@Service("ecoService")
public class ECOServiceImpl implements ECOService{
	@Resource(name="equipmentDao")
	private  EquipmentDao equipmentDao;
	@Resource(name = "equMoldDao")
	private EquMoldDao equMoldDao;
	@Resource(name="stateMinDao")
	private StateMinDao stateMinDao;
	@Resource(name="stateDayDao")
	private StateDayDao stateDayDao;
	@Resource(name="stateWeekDao")
	private StateWeekDao stateWeekDao;
	@Resource(name="stateMonthDao")
	private StateMonthDao stateMonthDao;
	@Resource(name="chargeWeekDao")
	private ChargeWeekDao chargeWeekDao;
	@Resource(name="chargeMonthDao")
	private ChargeMonthDao chargeMonthDao;
	/**
	 * 获得同类设备日综合数据
	 * @param equMoldId
	 * @param startDate
	 * @param endDate
	 * @param model
	 */
	@Override
	public void getEquModeAbilityDayData(int equMoldId, String startDate, String endDate, Map<String, Object> model) {
		DecimalFormat  df=new DecimalFormat ("0.0");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String equMold="";int totalEqus=0;double averageFullRate=0.0;String freeEqu="";
		List<String> equNames=new ArrayList<String>();//设备
		List<Double> startRateLine=new ArrayList<Double>();//设备开动率
		List<Double> fullRateLine=new ArrayList<Double>();//设备满载率
		List<String> states=Arrays.asList(new String[]{"停机","满载"});
		try{
			EquMold em=equMoldDao.get(equMoldId);
			if(em!=null){
				equMold=em.getEquType();
			}
			List<Equipment> equs=equipmentDao.findByEquModlId(equMoldId);
			totalEqus=equs.size();
			if(totalEqus!=0){
			    Calendar start=Calendar.getInstance();
		        Calendar end=(Calendar) start.clone();
		        start.setTime(sdf.parse(startDate));
		        end.setTime(sdf.parse(endDate));
				int aeraDay=(int) ((end.getTimeInMillis()-start.getTimeInMillis())/(24*3600*1000L));
				   for(String state:states){
					   for(Equipment e:equs){
						   if(state.equals("停机")){
							   equNames.add(e.getEquName());
						   }
						   double duration=stateDayDao.getTotalWorkTime(e.getId(), startDate, endDate, state);
							if(duration!=0){
					    		if(state.equals("停机")){
					    			startRateLine.add(Double.parseDouble(df.format((aeraDay*24-duration/3600)/(aeraDay*24)*100)));
					    		}else{
					    			fullRateLine.add(Double.parseDouble(df.format(duration/3600/(aeraDay*24)*100)));
					    		}
							}else{
						  		if(state.equals("停机")){
						  			startRateLine.add(100.0);
					    		}else{
					    			fullRateLine.add(0.0);
					    		}
						    }
					   }
				   }
			}
			//平均满载率
			int total=fullRateLine.size();
			if(total!=0){
				double sum=0.0;
				for(Double d:fullRateLine){
					sum+=d/100;
				}
				averageFullRate=Double.parseDouble(df.format(sum/total*100));
			}
		   //最大空闲设备
            int minIndex=0;
			double minStartRate=startRateLine.get(0); 
			for(int i=0;i<startRateLine.size();i++){
				if(minStartRate>startRateLine.get(i)){
					minStartRate=startRateLine.get(i);
					minIndex=i;
				}
			}
			freeEqu=equNames.get(minIndex);
					
			model.put("startDate", startDate);
			model.put("endDate", endDate);
			model.put("equMold", equMold);
			model.put("totalEqus", totalEqus);
			model.put("averageFullRate", averageFullRate+"%");
			model.put("freeEqu", freeEqu);
			model.put("equNames", equNames);
			model.put("startRateLine", startRateLine);
			model.put("fullRateLine", fullRateLine);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	/**
	 *获取同类设备周数据
	 * @param equMoldId
	 * @param belongYear
	 * @param startWeek
	 * @param endWeek
	 * @param model
	 */
	@Override
	public void getEquModeAbilityWeekData(int equMoldId, int belongYear, int startWeek, int endWeek, Map<String, Object> model) {
		DecimalFormat  df=new DecimalFormat ("0.0");
		String equMold="";int totalEqus=0;double averageFullRate=0.0;String freeEqu="";
		List<String> equNames=new ArrayList<String>();//设备
		List<Double> startRateLine=new ArrayList<Double>();//设备开动率
		List<Double> fullRateLine=new ArrayList<Double>();//设备满载率
		List<String> states=Arrays.asList(new String[]{"停机","满载"});
		EquMold em=equMoldDao.get(equMoldId);
		if(em!=null){
			equMold=em.getEquType();
		}
		List<Equipment> equs=equipmentDao.findByEquModlId(equMoldId);
		totalEqus=equs.size();
		int totalDay=(endWeek-startWeek)*7;
		for(String state:states){
			  for(Equipment e:equs){
				   if(state.equals("停机")){
					   equNames.add(e.getEquName());
				   }
				   StateWeek sweek=stateWeekDao.getdurationByStateAndDate(e.getId(), belongYear, startWeek, endWeek, state);
			       if(sweek!=null){
				    		if(state.equals("停机")){
				    			startRateLine.add(Double.parseDouble(df.format(((totalDay*24-sweek.getDuration()/3600)/(totalDay*24))*100)));
				    		}else{
				    			fullRateLine.add(Double.parseDouble(df.format(((sweek.getDuration()/3600)/(totalDay*24))*100)));
				    		}
						}else{
					  		if(state.equals("停机")){
					  			startRateLine.add(0.0);
			    		}else{
			    			    fullRateLine.add(0.0);
			    		}
			       }
			   }
		   }
		 //平均满载率
			int total=fullRateLine.size();
			if(total!=0){
				double sum=0.0;
				for(Double d:fullRateLine){
					sum+=d/100;
				}
				averageFullRate=Double.parseDouble(df.format(sum/total*100));
			}
		   //最大空闲设备
           int minIndex=0;
			double minStartRate=startRateLine.get(0); 
			for(int i=0;i<startRateLine.size();i++){
				if(minStartRate>startRateLine.get(i)){
					minStartRate=startRateLine.get(i);
					minIndex=i;
				}
			}
			freeEqu=equNames.get(minIndex);
					
			model.put("startDate", belongYear+"年第"+startWeek+"周");
			model.put("endDate", belongYear+"年第"+endWeek+"周");
			model.put("equMold", equMold);
			model.put("totalEqus", totalEqus);
			model.put("averageFullRate", averageFullRate+"%");
			model.put("freeEqu", freeEqu);
			model.put("equNames", equNames);
			model.put("startRateLine", startRateLine);
			model.put("fullRateLine", fullRateLine);
	}
	/**
	 * 获取同类设备月数据
	 * @param equMoldId
	 * @param belongYear
	 * @param startMonth
	 * @param endMonth
	 * @param model
	 */
	@Override
	public void getEquModeAbilityMonthData(int equMoldId, int belongYear, int startMonth, int endMonth, Map<String, Object> model) {
			DecimalFormat  df=new DecimalFormat ("0.0");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			String equMold="";int totalEqus=0;double averageFullRate=0.0;String freeEqu="";int areaDays=0;
			List<String> equNames=new ArrayList<String>();//设备
			List<Double> startRateLine=new ArrayList<Double>();//设备开动率
			List<Double> fullRateLine=new ArrayList<Double>();//设备满载率
			List<String> states=Arrays.asList(new String[]{"停机","满载"});
			EquMold em=equMoldDao.get(equMoldId);
			if(em!=null){
				equMold=em.getEquType();
			}
			List<Equipment> equs=equipmentDao.findByEquModlId(equMoldId);
			totalEqus=equs.size();
			try {
				String startDate = sdf.format(sdf.parse(belongYear+"-"+startMonth));
				String endDate=sdf.format(sdf.parse(belongYear+"-"+endMonth));
				for(int month=startMonth;month<=endMonth;month++){
					Date belongDate=sdf.parse(belongYear+"-"+month);
					Calendar ca = Calendar.getInstance();  
					ca.setTime(belongDate);
					areaDays+=ca.getActualMaximum(Calendar.DAY_OF_MONTH);
				}
				for(String state:states){
					  for(Equipment e:equs){
						   if(state.equals("停机")){
							   equNames.add(e.getEquName());
						   }
						   double duration=stateMonthDao.getTotalWorkTime(e.getId(), startDate, endDate, state);
							if(duration!=0){
					    		if(state.equals("停机")){
					    			startRateLine.add(Double.parseDouble(df.format(((areaDays*24-duration/3600)/(areaDays*24))*100)));
					    		}else{
					    			fullRateLine.add(Double.parseDouble(df.format(((duration/3600)/(areaDays*24))*100)));
					    		}
							}else{
						  		if(state.equals("停机")){
						  			startRateLine.add(100.0);
					    		}else{
					    			fullRateLine.add(0.0);
					    		}
						    }
					  }
				}
				 //平均满载率
				int total=fullRateLine.size();
				if(total!=0){
					double sum=0.0;
					for(Double d:fullRateLine){
						sum+=d/100;
					}
					averageFullRate=Double.parseDouble(df.format(sum/total*100));
				}
			   //最大空闲设备
	           int minIndex=0;
				double minStartRate=startRateLine.get(0); 
				for(int i=0;i<startRateLine.size();i++){
					if(minStartRate>startRateLine.get(i)){
						minStartRate=startRateLine.get(i);
						minIndex=i;
					}
				}
				freeEqu=equNames.get(minIndex);
						
				model.put("startDate", startDate);
				model.put("endDate", endDate);
				model.put("equMold", equMold);
				model.put("totalEqus", totalEqus);
				model.put("averageFullRate", averageFullRate+"%");
				model.put("freeEqu", freeEqu);
				model.put("equNames", equNames);
				model.put("startRateLine", startRateLine);
				model.put("fullRateLine", fullRateLine);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 设备老化周分析
	 * @param equId
	 * @param belongYear
	 * @param startWeek
	 * @param endWeek
	 * @param model
	 */
	@Override
	public void getEquAgingAnalysisWeekData(int equId, int belongYear, int startWeek, int endWeek, Map<String, Object> model) {
		     String equName="";
		     String  str1="设备能耗趋势正常，未见明显老化。"; String str2="设备能耗趋于增值，有老化风险。";
		     List<String> weeks=new ArrayList<String>();
		     List<Integer> rateDatas=new ArrayList<Integer>();
		     Equipment equ=equipmentDao.get(equId);
		     if(equ!=null){
		    	 equName=equ.getEquName()+"("+equ.getEquNo()+")";
		      }
			 for(int week=startWeek;week<=endWeek;week++){
					weeks.add(week+"周");
				    ChargeWeek cw=chargeWeekDao.getCompByDate(equId,belongYear,week,"N");
				    StateWeek sw=stateWeekDao.getStateWeekByStateAndDate(equId,belongYear,week,"满载");
					if(sw!=null){
						int rate=(int) (cw.getRelativeComp()/(sw.getDuration()/(7*24*3600)));
						rateDatas.add(rate);
					}else{
						rateDatas.add(0);
					}
			 }
			 //计算周范围内最大值与最小值 判断设备是否老化
			 int min=Collections.min(rateDatas);
			 int max=Collections.max(rateDatas);
			 if(max-min>200000){
				 model.put("str", str2);
			 }else{
				 model.put("str", str1);
			 }
			 model.put("startDate", belongYear+"年第"+startWeek+"周");
			 model.put("endDate", belongYear+"年第"+endWeek+"周");
		     model.put("equName", equName);
		     model.put("weeks", weeks);
		     model.put("rateDatas", rateDatas);
	}
	/**
	 * 设备老化月分析
	 * @param equId
	 * @param belongYear
	 * @param startMonth
	 * @param endMonth
	 * @param model
	 */
	@Override
	public void getEquAgingAnalysisMonthData(int equId, int belongYear, int startMonth, int endMonth, Map<String, Object> model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); 
		String equName="";
	     String  str1="设备能耗趋势正常，未见明显老化。"; String str2="设备能耗趋于增值，有老化风险。";
	     List<String> months=new ArrayList<String>();
	     List<Integer> rateDatas=new ArrayList<Integer>();
	 	try {
		     Equipment equ=equipmentDao.get(equId);
		     if(equ!=null){
		    	 equName=equ.getEquName()+"("+equ.getEquNo()+")";
		      }
		     String startDate = sdf.format(sdf.parse(belongYear+"-"+startMonth));
			 String endDate=sdf.format(sdf.parse(belongYear+"-"+endMonth));
	         for(int month=startMonth;month<=endMonth;month++){
		    	    months.add(month+"月");			
					Date belongDate = sdf.parse(belongYear+"-"+month);
					String date=sdf.format(belongDate);
					Calendar ca = Calendar.getInstance();  
					ca.setTime(belongDate);
					int  areaDays=ca.getActualMaximum(Calendar.DAY_OF_MONTH);
					ChargeMonth cm=chargeMonthDao.getCompByDate(equId, date, "", "N");
					StateMonth sm=stateMonthDao.getStateMonthByDate(equId, "满载",date );
					if(sm!=null){
						int rate=(int) (cm.getRelativeComp()/(sm.getDuration()/(areaDays*24*3600)));
						rateDatas.add(rate);
					}else{
						rateDatas.add(0);
					}
			  }
		     //计算周范围内最大值与最小值 判断设备是否老化
			 int min=Collections.min(rateDatas);
			 int max=Collections.max(rateDatas);
			 if(max-min>2000000){
				 model.put("str", str2);
			 }else{
				 model.put("str", str1);
			 }
			 model.put("startDate", startDate);
			 model.put("endDate", endDate);
		     model.put("equName", equName);
		     model.put("months", months);
		     model.put("rateDatas", rateDatas);
	 	} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
